package com.shigen.file.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.file.common.Common.Redis;
import com.shigen.file.config.ConfigProperty;
import com.shigen.file.config.TokenUtil;
import com.shigen.file.entity.UserInfo;
import com.shigen.file.exception.BusinessException;
import com.shigen.file.mapper.UserInfoMapper;
import com.shigen.file.service.IUserInfoService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <p>
 * 用户的信息 服务实现类
 * </p>
 *
 * @author shigen.fu
 * @since 2022-06-04
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

  @Resource
  private StringRedisTemplate stringRedisTemplate;
  @Resource
  private ConfigProperty configProperty;
  @Resource
  private TokenUtil tokenUtil;

  @Override
  public UserInfo getCurUserInfo() {
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (servletRequestAttributes != null) {
      HttpServletRequest request = servletRequestAttributes.getRequest();
      String token = request.getHeader("token");
      if (StrUtil.isNotEmpty(token)) {
        String key = Redis.TOKEN_PREFIX + tokenUtil.parseTokenWithTimestamp(token);
        String userinfoString = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(userinfoString)) {
          return JSONObject.parseObject(userinfoString, UserInfo.class);
        }
      }
    }

    if (configProperty.isLoginDebugEnable()) {
      return new UserInfo().setUserId(configProperty.getId()).setUserName(configProperty.getName());
    } else {
      throw new BusinessException("用户信息不存在");
    }
  }

}
